package com.wis.tools;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wis.TopologyDrive;
import com.wis.pool.redisCluster.MyJedisClusterPool;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import redis.clients.jedis.JedisCluster;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: traffic_wis
 * @author: fan
 * @Date: Created in 2018/12/24 14:56
 * @Modified By:
 */
public class CommonUtiles {
    /**
     * 判断是否取订正后的值
     *
     * @param str1 key值里面的时间
     * @param str2 订正的过期时间
     * @param num  计算的时次
     * @return 判断是否取订正后的值
     */
    public static boolean isFlagCalc(String str1, String str2, int num) {
        // String str = "201908041100";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
        double dou = 0;
        if (StringUtils.isNotBlank(str1)) {
            try {
                dou = ((double) ((dateFormat.parse(str2).getTime() - dateFormat.parse((Long.parseLong(str1) + (num * 10)) + "").getTime()) / 1000)) / 600;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (dou >= 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 日期转转字符串
     *
     * @param date
     * @return
     */
    public static String dateToStr(Date date) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        return str;
    }

    public static String mergeValue(String first, String second, String value, JedisCluster jedisCluster) {
        String tmpValue = jedisCluster.hget(first, second);
        if (StringUtils.isNotBlank(tmpValue)) {
            JSONArray features = JSON.parseObject(tmpValue).getJSONArray("features");
            JSONArray nowFeatures = JSON.parseObject(value).getJSONArray("features");
            features.addAll(nowFeatures);
            JSONObject newJsonData = new JSONObject();
            newJsonData.put("features", features);
            return newJsonData.toJSONString();
        }
        return null;
    }

    public static String mapToJson(Object str) {
        return str.toString().replaceAll(" ", "")
                .replaceAll("pile_id=", "\"pile_id\":\"")
                .replaceAll(",risk_index_type", "\",risk_index_type")
                .replaceAll("risk_index_type", "\"risk_index_type\"")
                .replaceAll("district_level", "\"district_level\"")
                .replaceAll("threshold11", "\"threshold11\"")
                .replaceAll("threshold12", "\"threshold12\"")
                .replaceAll("threshold13", "\"threshold13\"")
                .replaceAll("threshold14", "\"threshold14\"")
                .replaceAll("threshold21", "\"threshold21\"")
                .replaceAll("threshold22", "\"threshold22\"")
                .replaceAll("threshold23", "\"threshold23\"")
                .replaceAll("threshold24", "\"threshold24\"")
                .replaceAll("pac", "\"pac\"")
                .replaceAll("id=", "\"id\"=")
                .replaceAll("meteorology_type", "\"meteorology_type\"")
                .replaceAll("description", "\"description\"")
                .replaceAll("threshold=", "\"threshold\":")
                .replaceAll("color", "\"color\"")
                .replaceAll("status", "\"status\"")
                .replaceAll("delete_flag", "\"delete_flag\"")
                .replaceAll("'", "\"")
                .replaceAll("=", ":")
                .replaceAll(":,", ":\"\",");
    }

    /**
     * 某一个桩点卡值的选择
     *
     * @param key
     * @param id
     * @param list
     * @param kaZhiPointMap
     * @param kaZhiProMap
     * @param jsonArray
     * @return
     */
    public static JSONArray jsonKaZhiSelect(String key, String id, List list, Map<String, String> kaZhiPointMap, Map<String, String> kaZhiProMap, JSONArray jsonArray) {
        if (list.size() > 0 && kaZhiPointMap.size() > 0 && list.contains(id)) {
            // 按照桩点算
            if (StringUtils.isNotBlank(kaZhiPointMap.get(id)))
                return JSONObject.parseArray(mapToJson(kaZhiPointMap.get(id)));
        } else if (list.size() > 0 && kaZhiProMap.size() > 1 && list.contains(key.substring(0, 6))) {
            // 按照pac码算    县
            if (StringUtils.isNotBlank(kaZhiProMap.get(key.substring(0, 6))))
                return JSONObject.parseArray(mapToJson(kaZhiProMap.get(key.substring(0, 6))));
        } else if (list.size() > 0 && kaZhiProMap.size() > 1 && list.contains(key.substring(0, 2) + "0000")) {
            // 按照省份计算
            if (StringUtils.isNotBlank(kaZhiProMap.get(key.substring(0, 2) + "0000")))
                return JSONObject.parseArray(mapToJson(kaZhiProMap.get(key.substring(0, 2) + "0000")));
        } else {
            // 默认按全国的计算
            return jsonArray;
        }
        return jsonArray;
    }

    public static JSONArray jsonKaZhiRevSelect(String key, List list, Map<String, String> kaZhiProMap, JSONArray jsonArray) {
        if (list.size() > 0 && kaZhiProMap.size() > 1 && list.contains(key.substring(0, 6))) {
            // 按照pac码算    县
            if (StringUtils.isNotBlank(kaZhiProMap.get(key.substring(0, 6))))
                return JSONObject.parseArray(mapToJson(kaZhiProMap.get(key.substring(0, 6))));
        } else if (list.size() > 0 && kaZhiProMap.size() > 1 && list.contains(key.substring(0, 2) + "0000")) {
            // 按照省份计算
            if (StringUtils.isNotBlank(kaZhiProMap.get(key.substring(0, 2) + "0000")))
                return JSONObject.parseArray(mapToJson(kaZhiProMap.get(key.substring(0, 2) + "0000")));
        } else {
            // 默认按全国的计算
            return jsonArray;
        }
        return jsonArray;
    }

    public static void deleteRevKey(JedisCluster jedisCluster, String key, String yaoSuKey) {
        if (jedisCluster == null) jedisCluster = MyJedisClusterPool.getRedisClusterObject();
        jedisCluster.hdel(key, yaoSuKey);
    }

    /**
     * @param url
     * @return
     * @description 通过post http链接获取相关的数据
     */
    public JSONObject getPostHttpJson(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        JSONObject jsonObject = new JSONObject();
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("charset", "utf-8");
            String body = "{\"district_level\":0,\"pac\":100000}";
            httpPost.setEntity(new StringEntity(body, "utf-8"));
            response = httpClient.execute(httpPost);
            HttpEntity entry = response.getEntity();
            String result = EntityUtils.toString(entry);
            jsonObject = JSON.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
            return jsonObject;
        }
    }

    /**
     * @param url
     * @return
     * @description 通过http链接获取相关的数据
     */
    public List getHttpList(String url) {
        CloseableHttpClient httpClient = null;
        List list = new LinkedList();
        try {
            httpClient = HttpClients.createDefault();
            String result = EntityUtils.toString(httpClient.execute(new HttpGet(url)).getEntity());
            // list = Arrays.asList(request);
            String[] strings = result.split(",", -1);
            for (String tmp : strings) {
                list.add(tmp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpClient);
            return list;
        }
    }

    /**
     * @param url
     * @return
     * @description 通过http链接获取相关的数据
     */
    public JSONObject getHttpJsonObject(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        JSONObject parse = new JSONObject();
        try {
            httpClient = HttpClients.createDefault();
            HttpGet request = new HttpGet(url);
            response = httpClient.execute(request);
            HttpEntity entry = response.getEntity();
            String result = EntityUtils.toString(entry);
            parse = JSON.parseObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
            return parse;
        }
    }

    /**
     * @param filePath
     * @return
     * @descrition 获取经度和纬度的值，返回的map的key：桩点id，值为经纬度的集合
     */
    public Map getLonLatValue(String filePath) {
        BufferedReader bufferedReader = null;
        Map mapTxt = new HashMap();
        try {
            // bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "utf8"));
            bufferedReader = new BufferedReader(new InputStreamReader(TopologyDrive.class.getClassLoader().getResourceAsStream(filePath)));
            String string;
            while ((string = bufferedReader.readLine()) != null) {
                String[] strings = string.split(",", -1);
                mapTxt.put(strings[1], new String[]{strings[2], strings[3]});
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return mapTxt;
        }
    }

    public List getFilter(String filePath) {
        BufferedReader bufferedReader = null;
        List list = new LinkedList();
        try {
            // bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "utf8"));
            String string;
            bufferedReader = new BufferedReader(new InputStreamReader(TopologyDrive.class.getClassLoader().getResourceAsStream(filePath)));
            while ((string = bufferedReader.readLine()) != null) {
                list.add(string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;
        }
    }


    /**
     * @param filePath 文件路径
     * @return
     * @descrition 获取pac码，map集合的key为桩点id，value为pac码
     */
    public Map getPACValue(String filePath) {
        BufferedReader bufferedReader = null;
        Map mapPAC = new HashMap();
        try {
            // bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), "utf8"));
            bufferedReader = new BufferedReader(new InputStreamReader(TopologyDrive.class.getClassLoader().getResourceAsStream(filePath)));
            String string;
            while ((string = bufferedReader.readLine()) != null) {
                String[] strings = string.split(",", -1);
                mapPAC.put(strings[1], strings[9]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return mapPAC;
        }
    }
}
